package com.thunder.kocho.devaloka

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import com.thunder.kocho.R

class DevalokaLayout : LinearLayout {

    private val devaloka: Devaloka
    private var isReady = false
    private val defaultColor: Int

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context,
        attrs,
        defStyle
    ) {
        val typeArray =
            context.obtainStyledAttributes(attrs, R.styleable.DevalokaLayout, defStyle, 0)
        val color = typeArray.getColor(R.styleable.DevalokaLayout_devalokaColor, Color.BLUE)
        val cornerRadius = typeArray.getFloat(R.styleable.DevalokaLayout_devalokaCornerRadius, 10f)
        val borderWidth = typeArray.getFloat(R.styleable.DevalokaLayout_devalokaBorderWidth, 15f)
        val duration = typeArray.getInt(R.styleable.DevalokaLayout_devalokaDuration, 3000)
        defaultColor =
            typeArray.getColor(R.styleable.DevalokaLayout_devalokaDefaultColor, Color.WHITE)
        typeArray.recycle()
        devaloka = Devaloka(borderWidth, cornerRadius, color, duration.toLong())
        setBackgroundColor(defaultColor)
    }

    fun onFocusChange(isFocus: Boolean) {
        if (!isReady) {
            return
        }
        if (isFocus) {
            background = devaloka
            devaloka.start()
        } else {
            if (devaloka.isRunning) {
                devaloka.stop()
            }
            setBackgroundColor(defaultColor)
        }
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        devaloka.setBounds(l, t, r, b)
        isReady = true
    }

    override fun requestLayout() {
        super.requestLayout()
        isReady = false
    }

    override fun onVisibilityChanged(changedView: View, visibility: Int) {
        super.onVisibilityChanged(changedView, visibility)
        if (!isReady) {
            return
        }
        when (visibility) {
            VISIBLE -> devaloka.start()
            INVISIBLE, GONE -> devaloka.stop()
        }
    }
}